<template>
  <a-modal
    :destroy-on-close="true"
    :mask-closable="false"
    :visible="visible"
    :title="title"
    :confirm-loading="loading"
    :width="700"
    @cancel="handleClose"
    @ok="handleSubmit"
  >
    <a-form ref="formRef" :model="formData" :rules="formRules" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
      <a-form-item label="Key" name="infoKey">
        <a-input v-model:value="formData.infoKey" placeholder="请输入Key" />
      </a-form-item>
      <a-form-item label="标题" name="title">
        <a-input v-model:value="formData.title" placeholder="请输入文章标题" />
      </a-form-item>
      <a-form-item label="内容" name="content">
        <editor v-model:value="formData.content" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script name="ContentInfoEdit" lang="ts" setup>
import { getInfo, saveInfo, updateInfo } from "@/api/content/info";
import { enum2Value } from "@/utils/conver";

const emit = defineEmits(["reload"]);

const title = ref("添加信息");
const loading = ref(false);
const visible = ref(false);

const formRef = ref();
const formData: any = reactive({
  infoId: undefined
});
const formRules = reactive({
  infoKey: [{ required: true, message: "请输入KEY", trigger: "blur" }],
  title: [{ required: true, message: "请输入标题", trigger: "blur" }],
  content: [{ required: true, message: "请输入内容", trigger: "blur" }]
});

const handleGetInfo = (id: number) => {
  loading.value = true;
  getInfo(id)
    .then(response => {
      Object.assign(formData, enum2Value(response.data));
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleAdd = () => {
  title.value = "添加信息";
  Object.assign(
    formData,
    reactive({
      infoId: undefined,
      infoKey: "",
      title: "",
      content: ""
    })
  );
  visible.value = true;
};

const handleEdit = (id: number) => {
  handleGetInfo(id);
  title.value = "编辑信息";
  visible.value = true;
};

const handleClose = () => {
  formRef.value.resetFields();
  visible.value = false;
};

const handleSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      if (formData.infoId === undefined) {
        saveInfo(formData)
          .then(() => {
            antdMessage.success("添加成功");
            emit("reload");
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      } else {
        updateInfo(formData)
          .then(() => {
            antdMessage.success("编辑成功");
            emit("reload");
            handleClose();
          })
          .finally(() => {
            loading.value = false;
          });
      }
    })
    .catch(error => {
      console.log("error", error);
    });
};
defineExpose({ handleAdd, handleEdit });
</script>
